const BaseRest = require('./base.js');

/**
 * 用户标签管理
 * @type {module.exports}
 */
module.exports = class extends BaseRest {
  constructor(ctx) {
    super(ctx);
    // 重载，改变默认规则
    this.modelInstance = this.model('user_tag');
  }

  async getAction() {
    let data = {};
    const map = {};
    // 获取详情
    if (this.id) {
      map.id = this.id;
      data = await this.modelInstance.where(map).find();
      return this.success(data);
    }

    // 关键词
    const key = this.get('key');
    if (key) {
      map['title'] = ['like', '%' + key + '%'];
    }

    const page = this.get('page') || 1; // 页码
    const pageSize = this.get('pageSize') || 50; // 每页显示数量
    data = await this.modelInstance.where(map).page(page, pageSize).order('id asc').countSelect();
    return this.success(data);
  }

  async postAction() {
    const title = this.post('title');

    if (think.isEmpty(title)) {
      return this.fail(-1, '添加失败');
    }

    const tag = await this.modelInstance.where({title: title}).find();
    if (!think.isEmpty(tag)) {
      return this.fail(-1, '标签已经存在');
    }

    const ret = await this.modelInstance.add({title: title});
    return this.success(ret);
  }

  /**
	 * 删除内容
	 * @return {[type]} [description]
	 */
  async deleteAction() {
    if (!this.id) {
      return this.fail(1001, '记录不存在');
    }
    const rows1 = await this.model('user_tag_link').where({
      tag_id: this.id
    }).delete();

    const rows = await this.modelInstance.where({
      id: this.id
    }).delete();
    if (rows) {
      // await this.hook('contentDelete', {id: this.id});
      return this.success({
        affectedRows: rows
      }, '删除成功');
    } else {
      return this.fail(1000, '删除失败');
    }
  }
};
